//
//  FCScanCodeVC.m
//  FundChain
//
//  Created by 肖浩然的mac on 2018/3/1.
//  Copyright © 2018年 RUIXIN. All rights reserved.
//

#import "FCScanCodeVC.h"
#import <AVFoundation/AVFoundation.h>
#import "FCScanPreview.h"
#import "FCWalletSendVC.h"
#import <SafariServices/SafariServices.h>
#import "FCSendAndReceiveVC.h"
#define IS_VAILABLE_IOS8  ([[[UIDevice currentDevice] systemVersion] intValue] >= 8)
@interface FCScanCodeVC ()<AVCaptureMetadataOutputObjectsDelegate>{
    UIView     *_viewNav;
    
}
// 1.输入设备   摄像头   键盘   鼠标  麦克风
/* 输入设备 */
@property (strong, nonatomic) AVCaptureDeviceInput *deviceInput;
// 2.输出设备  -->解析数据
/* 输出设备  Metadata:元数据*/
@property (strong, nonatomic) AVCaptureMetadataOutput *output;
// 3.会话  -->连接输入和输出设备
/* 会话 */
@property (strong, nonatomic) AVCaptureSession *session;
// 4.预览的图层
/* 图层 */
@property (strong, nonatomic) AVCaptureVideoPreviewLayer *previewLayer;

/* 自定义界面 */
@property (strong, nonatomic) FCScanPreview  *preview;

@end

@implementation FCScanCodeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [FCLocalUserHelper saveIsMainVC:@"0"];
    [self setNav];
    self.view.backgroundColor = kWhiteColor;
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if(authStatus == AVAuthorizationStatusDenied){
        if (IS_VAILABLE_IOS8) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:Localized(@"相机权限") message:Localized(@"请在iPhone的\"设置->隐私->相机\"选项中,允许\"FundChain\"访问您的相机.") preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:Localized(@"好") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }]];
            [alert addAction:[UIAlertAction actionWithTitle:Localized(@"去设置") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                if ([self canOpenSystemSettingView]) {
                    [self systemSettingView];
                }
            }]];
            [self presentViewController:alert animated:YES completion:nil];
        } else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:Localized(@"相机权限") message:Localized(@"请在iPhone的\"设置->隐私->相机\"选项中,允许\"FundChain\"访问您的相机.") delegate:nil cancelButtonTitle:Localized(@"好") otherButtonTitles:nil];
            [alert show];
        }
        
        return;
    }
    
    [self setScanCode];
    
    NSString *coinsStr;
    
    switch ([self.walletId integerValue]) {
        case 1001:
        {
            coinsStr = Localized(@"比特币");
        }
            break;
        case 1005:
        {
            coinsStr = Localized(@"莱特币");
        }
            break;
        case 1006:
        {
            coinsStr = Localized(@"比特币现金");
        }
            break;
        case 1009:
        {
            coinsStr = Localized(@"加密现金币");
        }
            break;
        case 1010:
        {
            coinsStr = Localized(@"零币");
        }
            break;
            
        default:
            break;
    }
    
    
    UILabel *label = [UILabel new];
    [self.view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-100);
        make.centerX.mas_equalTo(0);
        make.left.mas_equalTo(30);
        make.right.mas_equalTo(-30);
    }];
    label.text = [NSString stringWithFormat:@"%@ %@%@",Localized(@"请将"),coinsStr,Localized(@"地址二维码放入框内, 即可自动扫描")];
    label.textColor = kWhiteColor;
    label.font = Kfont(30);
    label.numberOfLines = 2;
    
    if (SCREEN_WIDTH == 320) {
        [label mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(-100*KScreenHeightScale1334);
        }];
    }
}
#pragma mark AVCaptureMetadataOutputObjectsDelegate
// 扫描到二维码数据时调用
// metadataObjects:扫描到的数据
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    
    // 移除图层
    [self.previewLayer removeFromSuperlayer];
    //    [self.preview removeFromSuperview];
    // 停止会话
    [self.session stopRunning];
    
    for (AVMetadataMachineReadableCodeObject * objc in metadataObjects) {
        // 二维码扫描出来的结果是字符串
        NSLog(@"%@",objc.stringValue);

            
        if (![objc.stringValue hasPrefix:@"http"]) {
            FCSendAndReceiveVC *sendAndReceiveVC = [FCSendAndReceiveVC new];
            sendAndReceiveVC.selectIndex = 0;
            sendAndReceiveVC.walletId = self.walletId;
            sendAndReceiveVC.isHomeQRcode = YES;
            sendAndReceiveVC.addressStr = objc.stringValue;
            sendAndReceiveVC.currentResultModel = self.currentResultModel;
            [self.navigationController pushViewController:sendAndReceiveVC animated:NO];
            
        }else if([objc.stringValue hasPrefix:@"http"]){
//            // 创建safari控制器
//            SFSafariViewController *safariVC = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:objc.stringValue]];
//            [self presentViewController:safariVC animated:YES
//                             completion:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }
        
        else{
//             [self.preview removeFromSuperview];
//            UILabel *showLabel = [UILabel new];
//            [self.view addSubview:showLabel];
//            [showLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.top.mas_equalTo(_viewNav.mas_bottom);
//                make.left.right.mas_equalTo(0);
//
//            }];
//            showLabel.numberOfLines = 3;
//            showLabel.text = objc.stringValue;
            [self.navigationController popViewControllerAnimated:YES];
            
        }
    }
    
    
}
#pragma mark-设置扫码
-(void)setScanCode{
    // 1.输入设备   摄像头   键盘   鼠标  麦克风
    // 1.1摄像头的设备  默认是后置摄像头
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    // 1.2创建摄像头输入设备
    self.deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    
    
    // 2.输出设备  -->解析数据
    self.output = [[AVCaptureMetadataOutput alloc] init];
    // 设置代理
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // 3.会话  -->连接输入和输出设备
    self.session = [[AVCaptureSession alloc] init];
    // 连接设备
    if ([self.session canAddInput:self.deviceInput]) {
        [self.session addInput:self.deviceInput];
    }
    
    if ([self.session canAddOutput:self.output]) {
        [self.session addOutput:self.output];
    }
    // 设置输出设备的解析数据的类型  -->QRCode  二维码
    self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
    // 4.预览的图层
    
    FCScanPreview *preview = [[FCScanPreview alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT)];
    preview.session = self.session;
    self.preview = preview;
    [self.view addSubview:preview];
    // 5.开启会话
    [self.session startRunning];
}

-(void)setNav{
    self.navigationController.navigationBarHidden = YES;
    _viewNav =[UIView new];
    [self.view addSubview:_viewNav];
    [_viewNav mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            if (iPhoneX) {
                
                make.left.right.top.mas_equalTo(self.view.safeAreaInsets);
                make.height.mas_equalTo(88);
            }else{
                make.left.right.mas_equalTo(0);
                make.height.mas_equalTo(64);
                make.top.mas_equalTo(0);
            }
        }else{
            make.left.right.mas_equalTo(0);
            make.height.mas_equalTo(64);
            make.top.mas_equalTo(0);
        }
        
    }];
    _viewNav.backgroundColor = kRedOrangeColor;
    
    UIButton *leftBtn = [UIButton new];
    [self.view addSubview:leftBtn];
    [leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15*KScreenWidthScale750);
        make.centerY.mas_equalTo(_viewNav.mas_centerY).offset(8);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    [leftBtn setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [leftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    //返回
    UILabel *backLabel = [UILabel new];
    
    [_viewNav addSubview:backLabel];
    [backLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(_viewNav);
        make.centerY.mas_equalTo(_viewNav.mas_centerY).offset(8);
    }];
    backLabel.text = Localized(@"扫描二维码");
    backLabel.textColor = [UIColor whiteColor];
    backLabel.font = KOverstrikingfont(36);
    
    //事件
    [leftBtn addTarget:self action:@selector(leftBtnClick) forControlEvents:UIControlEventTouchUpInside];
   
}
-(void)leftBtnClick{
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 *  是否可以打开设置页面
 *
 *  @return
 */
- (BOOL)canOpenSystemSettingView {
    if (IS_VAILABLE_IOS8) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            return YES;
        } else {
            return NO;
        }
    } else {
        return NO;
    }
}

/**
 *  跳到系统设置页面
 */
- (void)systemSettingView {
    if (IS_VAILABLE_IOS8) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}
@end
